package logger

import (
	"context"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
)

type mongoLogger struct {
	baselogger
	client *mongo.Collection
}

func NewMongoLogger() Logger {

	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
	clientOptions.Auth = &options.Credential{Username: "admin", Password: "123456"}

	// 连接到MongoDB
	client, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		panic(err)
	}

	// 检查连接
	err = client.Ping(context.TODO(), nil)
	if err != nil {
		panic(err)
	}

	mdb := client.Database("mychat")

	l := &mongoLogger{
		baselogger: baselogger{
			tag:      LoggerTagFluentd,
			logLevel: INFO,
		},
		client: mdb.Collection("log"),
	}
	l.Logger = l
	return l
}
func (l *mongoLogger) WithCustomTag(tag LoggerTag) Logger {
	nl := *l
	nl.tag = tag
	nl.Logger = &nl
	return &nl
}

func (l *mongoLogger) WithCustomStrTag(tagstr string) Logger {
	return l.WithCustomTag(LoggerTag(tagstr))
}

func (l *mongoLogger) LogEntry(logEntry map[string]any) {
	if l.client == nil {
		return
	}
	_, err := l.client.InsertOne(context.Background(), logEntry)
	if err != nil {
		log.Printf("mongo log request insert error||err=%v", err)
	}
}
